<template>
    <div class="user-add-container" v-if="dialogVisible">
        <!-- <el-dialog width="1000px" @close="handleCancel()" title="新增用户" :visible.sync="dialogVisible"> -->
        <el-card>
            <div slot="header" class="clearfix">
                <span>{{ isEditMode ? '编辑博客' : '新增博客' }}</span>
                <el-button @click="handleCancel" class="cancel-btn" @close="handleCancel()">返回</el-button>
            </div>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" style="text-align: left;">
                <el-form-item label="博客标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入博客标题"></el-input>
                </el-form-item>
                <el-form-item label="博客内容" prop="content">
                    <quill-editor style="width:100%;height: 400px; display: inline-block;"
                        v-model="form.content"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @blur="onEditorBlur"
                        @focus="onEditorFocus"
                        @change="onEditorChange"
                    />
                </el-form-item>
                <el-form-item label="博客类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择博客类型">
                        <el-option v-for="item in typesList" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit" :loading="loading">提交</el-button>
                    <el-button @click="handleCancel">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- </el-dialog> -->
    </div>
</template>

<script>
import { blogSave,blogTypesList,blogAdd } from '@/api/api'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
    name: 'BlogAdd',
    components: {
        quillEditor
    },
    data () {
        return {
            dialogVisible: false,
            isEditMode: false,
            form: {
                _id: '',
                title: '',
                content: '',
                type: '',
                status: 1,
            },
            rules: {
                title: [{ required: true, message: '请输入博客标题', trigger: 'blur' }],
                content: [{ required: true, message: '请输入博客内容', trigger: 'change' }],
                type: [{ required: true, message: '请选择博客类型', trigger: 'change' }]
            },
            loading: false,
            typesList: [],
            editorOption: {
                theme: 'snow',
                placeholder: '请输入内容...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'],
                        ['blockquote', 'code-block'],
                        [{ 'header': 1 }, { 'header': 2 }],
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                        [{ 'script': 'sub' }, { 'script': 'super' }],
                        [{ 'indent': '-1' }, { 'indent': '+1' }],
                        [{ 'direction': 'rtl' }],
                        [{ 'size': ['small', false, 'large', 'huge'] }],
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'font': [] }],
                        [{ 'align': [] }],
                        ['clean'],
                        ['link', 'image', 'video']
                    ]
                }
            }
        }
    },
    mounted () {
        
    },
    methods: {
        // 编辑器失去焦点
        onEditorBlur() {
            // 可以在这里添加失去焦点的处理逻辑
        },
        // 编辑器获得焦点
        onEditorFocus() {
            // 可以在这里添加获得焦点的处理逻辑
        },
        // 编辑器内容变化
        onEditorChange() {
            // 内容变化时会自动同步到form.content
        },
        typeBtn () {
            blogTypesList().then(res => {
                if (res.errCode == 0) {
                    this.typesList = res.data
                } else {
                    this.$message.error(res.errMsg)
                }
            })
        },
        openDialog (item) {
            // 重置表单
            this.$refs.formRef && this.$refs.formRef.resetFields();
            
            // 判断是新增还是编辑模式
            if (item && item._id) {
                this.isEditMode = true;
                // 设置表单数据（编辑模式）
                this.form = {
                    _id: item._id,
                    title: item.title || '',
                    content: item.content || '',
                    type: item.type || '',
                    status: item.status || 1
                };
            } else {
                this.isEditMode = false;
                // 重置表单（新增模式）
                this.form = {
                    _id: '',
                    title: '',
                    content: '',
                    type: '',
                    status: 1
                };
            }
            
            // 获取博客类型列表
            this.typeBtn();
            
            // 显示对话框
            this.dialogVisible = true;
        },
        handleSubmit () {
            this.loading = true;
            this.$refs.formRef.validate(valid => {
                if (valid) {
                    // 根据是否有_id判断是编辑还是新增
                    if (this.form._id) {
                        // 编辑模式
                        blogSave({
                            _id: this.form._id,
                            title: this.form.title,
                            content: this.form.content,
                            type: this.form.type,
                            status: this.form.status
                        }).then(res => {
                            this.loading = false;
                            if (res.errCode == 0) {
                                this.$message.success('编辑成功');
                                this.$refs.formRef.resetFields();
                                this.dialogVisible = false;
                                this.$emit('initTable');
                            } else {
                                this.$message.error(res.errMsg);
                            }
                        }).catch(err => {
                            this.loading = false;
                            this.$message.error('操作失败，请重试');
                            console.error(err);
                        });
                    } else {
                        // 新增模式
                        blogAdd({
                            title: this.form.title,
                            content: this.form.content,
                            type: this.form.type,
                            status: this.form.status
                        }).then(res => {
                            this.loading = false;
                            if (res.errCode == 0) {
                                this.$message.success('新增成功');
                                this.$refs.formRef.resetFields();
                                this.dialogVisible = false;
                                this.$emit('initTable');
                            } else {
                                this.$message.error(res.errMsg);
                            }
                        }).catch(err => {
                            this.loading = false;
                            this.$message.error('操作失败，请重试');
                            console.error(err);
                        });
                    }
                } else {
                    this.loading = false;
                    console.log('校验失败');
                }
            });
        },
        handleCancel () {
            this.$refs.formRef.resetFields()
            this.dialogVisible = false
        },
        // 图片上传处理
        
    }
}
</script>

<style lang="scss" scoped>
.user-add-container {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.cancel-btn {
  float: right;
}

.user-form {
  padding: 20px 0;
}

.avatar-uploader {
  margin-top: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}

.avatar-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}
</style>